package com.xushi.controller;

import com.xushi.bean.ActivityStateBean;
import com.xushi.bean.State;
import com.xushi.model.Activity;
import com.xushi.model.UserTemplate;
import com.xushi.service.ActivityService;
import com.xushi.service.StorageService;
import com.xushi.service.UserTemplateService;
import com.xushi.service.impl.QRCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("/activity")
public class ActivityController {
    private static final String activityQrCodeSuffix = "_activity.png";
    private static final String rankQrCodeSuffix = "_playerRank.png";

    private static final String interH5Page = "https://www.wxahd.com/isActivityStart?";

    private static final String gradeRankPage = "https://www.wxahd.com/playerRank?";
    @Autowired
    QRCodeGenerator qrCodeGenerator;
    @Autowired
    private StorageService storageService;
    @Autowired
    private UserTemplateService userTemplateService;
    @Autowired
    private ActivityService activityService;
    @Value("${littleGame.returnURL}")
    private String returnURL;

    @GetMapping("/")
    @ResponseBody
    public String home() {
        return "Hello UserTemplate";
    }

    @PostMapping("/startActivity")
    @ResponseBody
    public HashMap<String, Object> startActivity(@RequestParam int userTemplateId, @RequestParam("startTime") String sStartTime,
                                                 @RequestParam("endTime") String sEndTime) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        String resId = "";
        HashMap<String, Object> result = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(sStartTime);
            endTime = sdf.parse(sEndTime);
        } catch (Exception e) {
            result.put("code", 2);
            result.put("message", e.toString());
            return result;
        }

        Timestamp currTime = new Timestamp(System.currentTimeMillis());

        if (endTime.before(startTime)) {
            result.put("code", 2);
            result.put("message", "结束时间早于开始时间");
            return result;
        } else if (currTime.after(endTime)) {
            result.put("code", 3);
            result.put("message", "结束时间早于当前时间");
            return result;
        }
        try {
            Timestamp tStart = new Timestamp(startTime.getTime());
            Timestamp tEnd = new Timestamp(endTime.getTime());
            UserTemplate userTemplate = userTemplateService.getUserTemplateById(userTemplateId);

            if (!CollectionUtils.isEmpty(activityService.getActiveActivitiesByUT(userTemplate))) {
                result.put("code", 4);
                result.put("message", "already have an active activity on this user template");
                return result;
            }

            Activity activity = activityService.startActivity(username, userTemplate, tStart, tEnd);
            resId = "" + activity.getId();
            String filename = activity.getId() + activityQrCodeSuffix;
            boolean isSuccess = qrCodeGenerator.encode(filename, interH5Page + "activityId=" + activity.getId());
            if (!isSuccess) {
                result.put("code", 2);
                result.put("message", "fail to generate qr code");
                return result;
            }

            String filename2 = activity.getId() + rankQrCodeSuffix;
            boolean isSuccess2 = qrCodeGenerator.encode(filename2, gradeRankPage + "activityId=" + activity.getId());
            if (!isSuccess2) {
                result.put("code", 2);
                result.put("message", "fail to generate qr code");
                return result;
            }
        } catch (Exception e) {
            result.put("code", 2);
            result.put("message", e.toString());
            return result;
        }
        result.put("code", 1);
        result.put("message", "启动活动成功");
        result.put("activityId", resId);
        return result;

    }

    @RequestMapping(value = "stopActivity", method = RequestMethod.GET)
    @ResponseBody
    public HashMap<String, Object> stopActivity(@RequestParam int activityId) {
        HashMap<String, Object> map = new HashMap<>();
        Activity activity = activityService.getActivityById(activityId);
        if (null == activity) {
            map.put("code", "1");
            map.put("message", "can not find the activity");
            return map;
        }

        if (!State.ACTIVE.getState().equals(activity.getState())) {
            map.put("code", "2");
            map.put("message", "the activity state is wrong");
            return map;
        }

        activity.setState(State.DELETED.getState());
        activityService.updateActivity(activity);
        map.put("code", "3");
        map.put("message", "stop successfully");
        return map;
    }

    @RequestMapping(value = "getQRCode", method = RequestMethod.GET)
    public void getQRCode(@RequestParam int activityId, @RequestParam int type,
                          HttpServletResponse response) throws IOException {
        try {
            String fileName = "";
            if (type == 0) {
                fileName = activityId + activityQrCodeSuffix;
            } else {
                fileName = activityId + rankQrCodeSuffix;
            }
            byte[] data = qrCodeGenerator.getQRCode(fileName);
            if (data != null) {
                response.setContentType("image/png");
                response.getOutputStream().write(data);
                return;
            }

        } catch (IOException e) {
            System.out.println(e);
        }
        response.getWriter().write("get QR code failed");
    }

    @GetMapping("downloadQRCode")
    @ResponseBody
    public void downloadQrCode(@RequestParam int activityId, @RequestParam int type,
                               HttpServletResponse response) throws IOException {
        try {
            String fileName = "";
            if (type == 0) {
                fileName = activityId + activityQrCodeSuffix;
            } else {
                fileName = activityId + rankQrCodeSuffix;
            }
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + "\"");
            byte[] data = qrCodeGenerator.getQRCode(fileName);
            if (data != null) {
                response.setContentType("image/png");
                response.getOutputStream().write(data);
                return;
            }

        } catch (IOException e) {
            System.out.println(e);
        }
        response.getWriter().write("get QR code failed");
    }

    @GetMapping("/getActivityState")
    @ResponseBody
    public ActivityStateBean getActivityState(@RequestParam("activityId") String activityId) {
        // activityId不允许是负数
        if (!activityId.matches("\\d+")) {
            return null;
        }
        try {
            int id = Integer.valueOf(activityId);

            Activity activity = activityService.getActivityById(id);
            if (ObjectUtils.isEmpty(activity)) {
                return new ActivityStateBean();
            }

            ActivityStateBean activityStateBean = new ActivityStateBean(activity, returnURL);
            return activityStateBean;
        } catch (Exception e) {
            return new ActivityStateBean(null, returnURL);
        }
    }

}
